﻿namespace blenderdriver
{
    internal class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("CallBlender!");

            var r = AsyncMain();
            while (!r.IsCompleted)
            {
                System.Threading.Thread.Sleep(100);
            }
        }

        static async Task AsyncMain()
        {
            string blend = "C:\\Program Files\\Blender Foundation\\Blender 3.3\\blender.exe";

            var python = System.IO.Path.GetFullPath("res\\testbake.py");
            await shell.CopyRes();

            await PrepareScene(shell.InMeshPath);
            await shell.CleanOutput();//清理输出目录

            //呼叫Blend
            await shell.CallBlendSilent(blend, python);

            BakeFinish(shell.ExrPath, shell.OutMeshPath);
        }

        //烘焙之前准备场景
        static async Task PrepareScene(string path)
        {
            //todo
            //convert from some 3d scene format to d:\\temp\inmesh
            //此处需要注意 blender使用右手坐标系

            //这里的testscene文件是从unity导出的，你可以从任何3d软件做这件事

            System.IO.Directory.Delete(path, true);
            System.IO.Directory.CreateDirectory(path);
            try
            {
                var file = System.IO.Directory.GetFiles("testscene", "*.*");
                foreach (var f in file)
                {
                    System.IO.File.Copy(f, path + "\\" + System.IO.Path.GetFileName(f));
                    Console.WriteLine("copy file:" + f);
                }
              
            }
            catch(Exception err)
            {
                Console.Error.WriteLine(err.ToString());
            }
            Console.WriteLine("====step1 PrepareScene done.====" );
        }

        //烘焙之后提取输出
        static async Task BakeFinish(string lightmap, string uvmeshpath)
        {
            Console.WriteLine("==>Bake Result:EXR" + lightmap);
            var size = new System.IO.FileInfo(lightmap).Length;
            Console.WriteLine("    lightmapfilesize:" + size);

            var files = System.IO.Directory.GetFiles(uvmeshpath, "*.ply");
            foreach(var f in files)
            {
                Console.WriteLine("==>Bake Result:Mesh:" + f);
            }

        }
    }

}